package com.example.helloworldtext2.activities;

import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.VideoView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.widget.ViewPager2;

import com.example.helloworldtext2.R;
import com.example.helloworldtext2.model.Article;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class TikTokVideoActivity extends AppCompatActivity {

    private ViewPager2 viewPager;
    private VideoAdapter videoAdapter;
    private List<Article> videoList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tiktok_video);

        initViews();
        loadVideoData();
    }

    private void initViews() {
        viewPager = findViewById(R.id.viewPager);
        videoList = new ArrayList<>();
        videoAdapter = new VideoAdapter();
        viewPager.setAdapter(videoAdapter);
        
        // 设置页面切换监听器
        viewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                // 当切换页面时，暂停当前播放的视频并播放新视频
                videoAdapter.playVideo(position);
            }
        });
    }

    private void loadVideoData() {
        // 添加提供的示例数据
        videoList.add(new Article(
                1573,
                "儿时记忆，你有见过老铁匠吗",
                "",
                "https://image.cengjifou.com/uploads/video/20240803/20240803152641a223e2962.mp4",
                "https://image.cengjifou.com/uploads/images/20240803/20240803152658e230e1153.png",
                "了不起的匠人",
                "https://image.cengjifou.com/uploads/images/20240706/20240706223050fc5ab4179.jpg",
                Arrays.asList("匠人精神", "非遗"),
                "60.698"
        ));

        videoList.add(new Article(
                1575,
                "拍了整整一年，往返八次，才拍下这家门口一条小路的春夏秋冬，四季不停的轮回，像极了我们这短暂且忙碌的一生",
                "",
                "https://image.cengjifou.com/uploads/video/20240803-m3u8/202408031538105205e0235.m3u8",
                "https://image.cengjifou.com/uploads/images/20240803/20240803153836432552572.png",
                "乡村小农人",
                "https://image.cengjifou.com/uploads/images/20250821/20250821104120599a69941.jpg",
                Arrays.asList("乡愁记忆"),
                "10.134"
        ));

        videoList.add(new Article(
                1576,
                "这是一张2020年电视剧《渴望》演员重聚时的合影",
                "34年前电视剧《渴望》开播，创造了空前绝后的收视奇迹，张凯丽、李雪健、蓝天野等剧中演员一炮而红，享誉全国",
                "https://image.cengjifou.com/uploads/video/20240803-m3u8-m3u8/2024080315440791e752507.m3u8",
                "https://image.cengjifou.com/uploads/images/20250623/20250623144522334644910.png",
                "年轻真好",
                "https://image.cengjifou.com/uploads/images/20250822/20250822104222e88cf2383.png",
                Arrays.asList("明星老照片", "老照片", "渴望"),
                "36.866667"
        ));

        videoAdapter.notifyDataSetChanged();
    }

    private class VideoAdapter extends RecyclerView.Adapter<VideoAdapter.VideoViewHolder> {

        private int currentPosition = 0;

        @NonNull
        @Override
        public VideoViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(TikTokVideoActivity.this)
                    .inflate(R.layout.item_video, parent, false);
            return new VideoViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull VideoViewHolder holder, int position) {
            Article article = videoList.get(position);
            holder.bind(article);
        }

        @Override
        public int getItemCount() {
            return videoList.size();
        }

        public void playVideo(int position) {
            currentPosition = position;
            // 在实际应用中，这里应该控制视频播放
        }

        class VideoViewHolder extends RecyclerView.ViewHolder {
            private VideoView videoView;
            private ImageView coverImage;
            private ImageView playButton;
            private TextView titleText;
            private TextView descriptionText;
            private TextView authorText;
            private ImageView likeButton;
            private TextView likeCount;
            private ImageView commentButton;
            private TextView commentCount;
            private ImageView collectButton;
            private ImageView shareButton;
            private ImageView userAvatar;
            private TextView videoDuration;
            private LinearLayout topicsContainer;

            public VideoViewHolder(@NonNull View itemView) {
                super(itemView);
                videoView = itemView.findViewById(R.id.videoView);
                coverImage = itemView.findViewById(R.id.coverImage);
                playButton = itemView.findViewById(R.id.playButton);
                titleText = itemView.findViewById(R.id.titleText);
                descriptionText = itemView.findViewById(R.id.descriptionText);
//                authorText = itemView.findViewById(R.id.authorText);
                likeButton = itemView.findViewById(R.id.likeButton);
                likeCount = itemView.findViewById(R.id.likeCount);
                commentButton = itemView.findViewById(R.id.commentButton);
                commentCount = itemView.findViewById(R.id.commentCount);
                collectButton = itemView.findViewById(R.id.collectButton);
                shareButton = itemView.findViewById(R.id.shareButton);
//                userAvatar = itemView.findViewById(R.id.userAvatar);
//                videoDuration = itemView.findViewById(R.id.videoDuration);
                topicsContainer = itemView.findViewById(R.id.topicsContainer);
            }

            public void bind(Article article) {
                titleText.setText(article.getTitle());
                descriptionText.setText(article.getDescription());
                authorText.setText(article.getAuthorName());
                likeCount.setText(String.valueOf(article.getLikeCount()));
                commentCount.setText(String.valueOf(article.getCommentCount()));
                videoDuration.setText(formatDuration(article.getDuration()));

                // 设置视频URI
                Uri videoUri = Uri.parse(article.getVideoUrl());
                videoView.setVideoURI(videoUri);

                // 视频准备好的监听器
                videoView.setOnPreparedListener(mp -> {
                    // 视频准备完成后自动播放
                    videoView.start();
                    playButton.setVisibility(View.GONE);
                    coverImage.setVisibility(View.GONE);
                });

                // 视频播放完成监听器
                videoView.setOnCompletionListener(mp -> {
                    // 播放完成后重新开始播放
                    videoView.start();
                    playButton.setVisibility(View.GONE);
                });

                // 清空话题容器
                topicsContainer.removeAllViews();
                
                // 添加话题标签
                List<String> topics = article.getTopics();
                for (String topic : topics) {
                    TextView topicView = new TextView(TikTokVideoActivity.this);
                    topicView.setText("#" + topic);
                    topicView.setTextColor(getResources().getColor(android.R.color.holo_blue_light));
                    topicView.setTextSize(12);
                    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                            LinearLayout.LayoutParams.WRAP_CONTENT,
                            LinearLayout.LayoutParams.WRAP_CONTENT
                    );
                    params.setMargins(0, 0, 16, 0);
                    topicView.setLayoutParams(params);
                    topicsContainer.addView(topicView);
                }

                // 设置点赞按钮点击事件
                likeButton.setOnClickListener(v -> {
                    article.setLiked(!article.isLiked());
                    if (article.isLiked()) {
                        likeButton.setImageResource(android.R.drawable.btn_star_big_on);
                        article.setLikeCount(article.getLikeCount() + 1);
                    } else {
                        likeButton.setImageResource(android.R.drawable.btn_star_big_off);
                        article.setLikeCount(article.getLikeCount() - 1);
                    }
                    likeCount.setText(String.valueOf(article.getLikeCount()));
                });

                // 设置收藏按钮点击事件
                collectButton.setOnClickListener(v -> {
                    article.setCollected(!article.isCollected());
                    if (article.isCollected()) {
                        collectButton.setImageResource(android.R.drawable.ic_menu_save);
                    } else {
                        collectButton.setImageResource(android.R.drawable.ic_menu_save);
                    }
                });

                // 设置播放按钮点击事件
                playButton.setOnClickListener(v -> {
                    if (videoView.isPlaying()) {
                        videoView.pause();
                        playButton.setVisibility(View.VISIBLE);
                    } else {
                        videoView.start();
                        playButton.setVisibility(View.GONE);
                        coverImage.setVisibility(View.GONE);
                    }
                });

                // 在实际应用中，这里应该加载视频和封面图片
                // 使用类似 Picasso 或 Glide 的库加载图片
                // 使用 VideoView 或 ExoPlayer 播放视频
            }

            private String formatDuration(String duration) {
                try {
                    double seconds = Double.parseDouble(duration);
                    int totalSeconds = (int) Math.round(seconds);
                    int minutes = totalSeconds / 60;
                    int remainingSeconds = totalSeconds % 60;
                    return String.format("%02d:%02d", minutes, remainingSeconds);
                } catch (NumberFormatException e) {
                    return "00:00";
                }
            }
        }
    }
}
        